package com.crab.c03queue;

/**
 * 队列 利用数组实现的循环队列
 */
public class MyQueue {
    public static void main(String[] args) throws Exception {
        MyQueue myQueue = new MyQueue(6);
        myQueue.enqueue(1);
        myQueue.enqueue(2);
        myQueue.enqueue(3);
        myQueue.enqueue(4);
        myQueue.enqueue(5);
        myQueue.output();
        System.out.println(myQueue.dequeue());
        System.out.println(myQueue.dequeue());
        myQueue.output();

    }


    private int[] array;
    private int front;
    private int rear;

    public MyQueue(int capacity) {
        this.array = new int[capacity];
    }

    public void enqueue(int element) throws Exception {
        // 队列满
        if ((rear + 1) % array.length == front) {
            throw new Exception("队列满");
        }
        array[rear] = element;
        rear = (rear + 1) % array.length;
    }

    public int dequeue() throws Exception {
        // 队列空
        if (rear == front) {
            throw new Exception("队列空");
        }
        int removeElement = front;
        front = (front + 1) % array.length;
        return removeElement;
    }

    public void output() {
        for (int i = front; i != rear; i = (i + 1) % array.length) {
            System.out.print(array[i]);
            System.out.print(' ');
        }
        System.out.println();
    }

}
